package com.taptech.doufu.ui.activity

import android.animation.Animator
import android.animation.AnimatorListenerAdapter
import android.animation.AnimatorSet
import android.animation.ObjectAnimator
import android.content.Context
import android.content.Intent
import android.graphics.Color
import android.graphics.Paint
import android.os.Build
import android.text.TextUtils
import android.view.Gravity
import android.view.LayoutInflater
import android.view.View
import android.widget.RelativeLayout
import android.widget.TextView
import android.widget.Toast
import androidx.core.content.ContextCompat
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.LinearLayoutManager
import com.alibaba.fastjson.JSON
import com.alibaba.fastjson.JSONObject
import com.google.android.material.bottomsheet.BottomSheetDialog
import com.google.gson.Gson
import com.taptech.doufu.R
import com.taptech.doufu.bean.TagBean
import com.taptech.doufu.constant.Constant
import com.taptech.doufu.constant.SPKey
import com.taptech.doufu.constant.ShareType
import com.taptech.doufu.constant.UmengEventName
import com.taptech.doufu.event.EventBusNovelReadRecord
import com.taptech.doufu.ktexpand.format
import com.taptech.doufu.model.novel.bean.*
import com.taptech.doufu.model.novel.gson.NovelDetailGson
import com.taptech.doufu.net.retrofit.api.RxJavaHelper
import com.taptech.doufu.presenter.novel.INovelDetailsView
import com.taptech.doufu.presenter.novel.NovelDetailsPresenter
import com.taptech.doufu.services.personalcenter.AccountService
import com.taptech.doufu.ui.activity.base.BaseMvpActivity
import com.taptech.doufu.ui.activity.weex.SimpleWeexActivity
import com.taptech.doufu.ui.adapter.NovelBookListAdapter
import com.taptech.doufu.ui.adapter.NovelHotCommentAdapter
import com.taptech.doufu.ui.adapter.NovelRecommendGridAdapter
import com.taptech.doufu.ui.dialog.DoubleBtnTiptDialog
import com.taptech.doufu.ui.view.FlowerDialogManager
import com.taptech.doufu.ui.view.GiftDialogManager
import com.taptech.doufu.ui.view.MyScrollView
import com.taptech.doufu.ui.view.choice.ChoiceUtils
import com.taptech.doufu.ui.view.countdownview.CustomCountDownTimer
import com.taptech.doufu.ui.view.countdownview.DateUtils
import com.taptech.doufu.util.*
import com.taptech.doufu.util.ShareUtil.Companion.shareText
import com.taptech.doufu.util.sp.DiaoBaoSharedPreferences
import com.taptech.doufu.weex.image.TFImageViewUtil
import com.taptech.doufu.weex.notification.QLXNotificationCenter
import kotlinx.android.synthetic.main.activity_novel_detail.*
import kotlinx.android.synthetic.main.activity_novel_detail.layHead
import kotlinx.android.synthetic.main.activity_novel_detail.layUserGrade
import kotlinx.android.synthetic.main.activity_novel_detail.svContent
import kotlinx.android.synthetic.main.activity_novel_detail.tvAttention
import kotlinx.android.synthetic.main.activity_user_detail.*
import kotlinx.android.synthetic.main.view_article_comment_item.*
import kotlinx.android.synthetic.main.view_buy_novel_activity.*
import kotlinx.android.synthetic.main.view_comment_item.*
import kotlinx.android.synthetic.main.view_novel_detail_bottom.*
import kotlinx.android.synthetic.main.view_novel_detail_title_bar.*
import kotlinx.android.synthetic.main.view_novel_detail_title_bar_2.*
import kotlinx.android.synthetic.main.view_novel_gift.*
import kotlinx.android.synthetic.main.view_novel_recommend_by_author.*
import kotlinx.android.synthetic.main.view_share_enter.*
import kotlinx.android.synthetic.main.view_share_enter.ivPostTip
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode
import rx.Observable
import java.util.concurrent.TimeUnit

class NovelDetailsActivity :BaseMvpActivity<NovelDetailsPresenter>(),INovelDetailsView{

    private var hotCommentAdapter:NovelHotCommentAdapter? = null
    private var timer:CustomCountDownTimer? = null
    private var shareDialog: BottomSheetDialog? = null
    private var canShowPosterTip = true
    private var isYouthModel = false

    @Subscribe(threadMode = ThreadMode.MAIN)
    fun updateReadRecord(event: EventBusNovelReadRecord) {
        if (mPresenter!=null && mPresenter.novelBean!=null &&
                event!=null&&event.novelId!=null&&event.sectionId!=null&&
                mPresenter.novelId == event.novelId.toInt()){
            mPresenter.novelBean.lastReadSectionId = event.sectionId.toInt()
            mPresenter.novelBean.lastReadPosition = event.position
        }
    }


    override fun getLayout(): Int {
        return R.layout.activity_novel_detail
    }

    override fun initPresenter(intent: Intent) {
        mPresenter = NovelDetailsPresenter(this,this,intent)
        setScheme()
        mPresenter.getNovelDetails()
    }

    /**
     * 设置App外部调用传递的参数
     */
    private fun setScheme() {
        val uri = intent.data
        if (uri != null) {
            val novelId = uri.getQueryParameter("id")
            if (!TextUtils.isEmpty(novelId)) {
                mPresenter.novelId = novelId?.toInt() ?: 0
            }
        }
    }



    override fun initView() {
        setStatusBarFullTransparent()
        val titleBarHeight = if (Build.VERSION.SDK_INT >= 21) ScreenUtil.dip2px(this, 44f)+ScreenUtil.getStatusHeight(this) else ScreenUtil.dip2px(this, 44f)
        val titleBarParams = RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.MATCH_PARENT, titleBarHeight)
        layTitleBar.layoutParams = titleBarParams
        layTitleBar2.layoutParams = titleBarParams
        layMakePoster.visibility = View.VISIBLE
        ScreenUtil.getBottomStatusHeight(this)
        EventBus.getDefault().register(this)
        QLXNotificationCenter.getInstance().addNotify("TFNovelTopicSet",this) { _, data ->
            val res = JSONObject.parseObject(data.toString())
            if (mPresenter.novelId == res.getIntValue("id")){
                val bean = NovelDetailGson()
                bean.topic = mPresenter.novelBean
                QLXNotificationCenter.getInstance().postNotify("TFNovelTopicGet",JSONObject.toJSON(bean))
            }
        }
        setShareTipAnimation()
        layRecommendAuthorReplace.setOnClickListener {
            mPresenter.getRecommendByAuthor()
        }
        layRecommendNovelReplace.setOnClickListener {
            mPresenter.getRecommendByNovel()
        }
        tvAttention.setOnClickListener {
            if (!AccountService.getInstance().checkAndLogin()) {
                return@setOnClickListener
            }
            if (tvAttention.text.toString() == "取关..." || tvAttention.text.toString() == "关注..."){
                return@setOnClickListener
            }
            if (mPresenter.hasAttention){
                tvAttention.text = "取关..."
            }else{
                tvAttention.text = "关注..."
            }
            mPresenter.attentionUser()
        }
        layCollect.setOnClickListener {
            if (!AccountService.getInstance().checkAndLogin()) {
                return@setOnClickListener
            }
            if (tvCollect.text.toString() == "取消收藏..." || tvCollect.text.toString() == "收藏中...") {
                return@setOnClickListener
            }
            if (mPresenter.hasCollect){
                tvCollect.text = "取消收藏..."
            }else{
                tvCollect.text = "收藏中..."
            }
            mPresenter.collectNovel()
        }
        layRead.setOnClickListener {
            val bean = mPresenter.novelBean
            val novelId = bean.id.toString()
            val sectionId = bean.lastReadSectionId.toString()
            val hasCollect = mPresenter.hasCollect
            val monthTicketSum = bean.month_ticket_sum
            NovelSectionDetailsActivity.startActivity(this@NovelDetailsActivity, novelId,sectionId,hasCollect,monthTicketSum,NovelDetailsActivity::class.java.simpleName)
        }
        layDownload.setOnClickListener {
            if (!AccountService.getInstance().checkAndLogin()) {
                return@setOnClickListener
            }

            if (isYouthModel) {
                Toast.makeText(this@NovelDetailsActivity,"青少年模式不支持该功能",Toast.LENGTH_LONG).show()
                return@setOnClickListener
            }

            if (mPresenter.novelBean.has_permissions > 0) {
                if (mPresenter.novelBean.article_num <= 0) {
                    Toast.makeText(this@NovelDetailsActivity,"该小说章节数为0，不能离线哦",Toast.LENGTH_LONG).show()
                    return@setOnClickListener
                }
                presentWeexView("TFNovel/TFOffLine.js?present=1&id=${mPresenter.novelId}")
            }else{
                if (!mPresenter.novelBean.length.isNullOrEmpty()) {
                    Toast.makeText(this@NovelDetailsActivity,"该小说未通过审核，不能离线哦",Toast.LENGTH_LONG).show()
                }
            }
        }
        btnBuyBook.setOnClickListener {
            if (!AccountService.getInstance().checkAndLogin()) {
                return@setOnClickListener
            }
            mPresenter.buyFullBook()
        }
        layCatalog.setOnClickListener {
            NovelDesToDetailActivity.startActivity(this,mPresenter.novelId)
        }
        layFlower.setOnClickListener {
            if (isYouthModel) {
                Toast.makeText(this@NovelDetailsActivity,"青少年模式不支持该功能",Toast.LENGTH_LONG).show()
                return@setOnClickListener
            }
            FlowerDialogManager.getInstance(this@NovelDetailsActivity,mPresenter.getProductionBean(),mPresenter.novelBean.shareUrl)
        }
        layReward.setOnClickListener {
            if (isYouthModel) {
                Toast.makeText(this@NovelDetailsActivity,"青少年模式不支持该功能",Toast.LENGTH_LONG).show()
                return@setOnClickListener
            }
            GiftDialogManager.getInstance(this@NovelDetailsActivity,mPresenter.getProductionBean())
        }
        layTicket.setOnClickListener {
            if (!AccountService.getInstance().checkAndLogin()) {
                return@setOnClickListener
            }
            if (isYouthModel) {
                Toast.makeText(this@NovelDetailsActivity,"青少年模式不支持该功能",Toast.LENGTH_LONG).show()
                return@setOnClickListener
            }
            presentWeexView("TFNovel/TFMonthTicket.js?present=1&id=${mPresenter.novelId}&count=${mPresenter.novelBean.month_ticket_sum}")
        }
        layRedEnvelope.setOnClickListener {
            var url = "TFRedEnvelope/TFREList.js?id=${mPresenter.novelId}&vip=${mPresenter.novelBean.is_vip}" +
                    "&authorID=${mPresenter.novelBean.user.userId}"
            var params = HashMap<String,String>()
            params["title"] = mPresenter.novelBean.title
            SimpleWeexActivity.startActivity(this@NovelDetailsActivity,url,params)
        }
        layArticleComment.setOnClickListener {
            var url = "vue/articalComment/TFArticalComment.js?novelId=${mPresenter.novelId}&isFromDetail=true"
            SimpleWeexActivity.startActivity(this@NovelDetailsActivity,url)
        }
        layComment.setOnClickListener {
            jumpToComment()
        }
        tvToAllComment.setOnClickListener {
            jumpToComment()
        }
        ivAuthorHead.setOnClickListener {
            if (!TextUtils.isEmpty(mPresenter.novelBean.user.userId)){
                UserDetailActivity.startActivity(this@NovelDetailsActivity,mPresenter.novelBean.user.userId.toInt())
            }
        }
        layShareRank.setOnClickListener {
            val novelDetail = mPresenter.novelBean
            val novelBean = NovelDetailSimpleBean()
            novelBean.id = novelDetail.id
            novelBean.title = novelDetail.title
            novelBean.images = novelDetail.images
            novelBean.des = StringUtil.filterEmoji(novelDetail.des,"")
            novelBean.shareUrl = novelDetail.shareUrl
            val url = "TFNovel/TFShareStatistics.js"
            SimpleWeexActivity.startActivity(this@NovelDetailsActivity,JSON.parseObject(Gson().toJson(novelBean)),url)
        }

        svContent.setOnScrollChangeListener { _, scrollY, _, _ ->
            if (scrollY < 300) {
                val alpha = 1f/300f * scrollY
                layTitleBar2.alpha = alpha
                layTitleBar.alpha = 1f - alpha
            }else{
                layTitleBar.alpha = 0f
                layTitleBar2.alpha = 1f
            }
        }

        svContent.setOnScrollStatusListener(object :MyScrollView.OnScrollStatusListener{
            override fun onScrollStop() {
                if (UIUtil.getLocalVisibleRect(this@NovelDetailsActivity, ivPostTip, 0)) {
                    setPosterTipAnimation()
                }

            }

            override fun onScrolling() {

            }

        })

        layBack.setOnClickListener {
            finish()
        }


        ivEdit.setOnClickListener {
            val bean = mPresenter.novelBean
            NewNovelCreateListTosActivity.startActivity(this@NovelDetailsActivity,"${bean.id}",bean.title)
        }

        layShare.setOnClickListener {
//            shareSystemDialog()
            shareMore()
        }
        layShareMore.setOnClickListener {
//            shareSystemDialog()
//            BrowseActivity.startActivity(this,"http://api.doufu.la/activity/springFestival2021")
            shareMore()
        }
        layShareWeixin.setOnClickListener {
            shareEvent(ShareType.Weixin)
            val shareBean = mPresenter.getShareBean()
            shareBean.social_type = ShareType.Weixin
            ShareUtils.thirdPartyShare(this@NovelDetailsActivity,shareBean)
        }
        layShareWeibo.setOnClickListener {
            shareEvent(ShareType.Weibo)
            val shareBean = mPresenter.getShareBean()
            shareBean.shartText = "我在＃豆花＃ 发现了一本好书《${mPresenter.novelBean.title}》，作者：${mPresenter.novelBean.user.name}，${if (mPresenter.novelBean.recommend_text.isNullOrEmpty()) "" else mPresenter.novelBean.recommend_text}阅读全文>${mPresenter.novelBean.shareUrl} #推文# @豆花阅读"
            shareBean.social_type = ShareType.Weibo
            ShareUtils.thirdPartyShare(this@NovelDetailsActivity,shareBean)
        }
        layShareQQ.setOnClickListener {
            shareEvent(ShareType.QQ)
            val shareBean = mPresenter.getShareBean()
            shareBean.social_type = ShareType.QQ
            ShareUtils.thirdPartyShare(this@NovelDetailsActivity,shareBean)
        }
        layMakePoster.setOnClickListener {
            shareEvent(ShareType.Poster)
            NovelPosterActivity.startActivity(this@NovelDetailsActivity,mPresenter.novelBean)
        }
    }

    private fun shareEvent(socialType: Int) {
        val map = HashMap<String, String>()
        map["type"] = "$socialType"
        TMAnalysis.event(this@NovelDetailsActivity, UmengEventName.NOVEL_DETAIL_SHARE_ACTION, map)
    }


    private fun setPosterTipAnimation() {
        if (canShowPosterTip) {
            canShowPosterTip = false
            setTipViewAnimation(ivPostTip,ScreenUtil.dip2px(this,22f).toFloat(),ScreenUtil.dip2px(this,18f).toFloat())

        }
    }

    private fun setShareTipAnimation() {
        setTipViewAnimation(ivShareTip,ScreenUtil.dip2px(this,38f).toFloat(),0f)
    }

    private fun setTipViewAnimation(view:View,x:Float,y:Float) {

        val animationAlphaStart = ObjectAnimator.ofFloat(view,"alpha",0f,1f)
        animationAlphaStart.addListener(object : AnimatorListenerAdapter() {
            override fun onAnimationEnd(animation: Animator?) {
                super.onAnimationEnd(animation)
                val animationEnd = ObjectAnimator.ofFloat(view,"alpha",1f,0f)
                animationEnd.duration = 500
                animationEnd.startDelay = 3000
                animationEnd.start()
            }
        })
        val animationScaleX = ObjectAnimator.ofFloat(view,"scaleX",0f,1f)
        val animationScaleY = ObjectAnimator.ofFloat(view,"scaleY",0f,1f)
        view.pivotX = x
        view.pivotY = y
        val animationSet = AnimatorSet()
        animationSet.duration = 500
        animationSet.startDelay = 1000
        animationSet.play(animationAlphaStart).with(animationScaleX).with(animationScaleY)
        animationSet.start()
    }

    private fun shareSystemDialog() {
        val shareBean = mPresenter.getShareBean()
        val desc = "我正在 豆花 App 看《" + shareBean.title + "》小说，99%女生都在用的耽美言情BL同人小说阅读器，邀请你跟我一起看!!! " + shareBean.shareUrl
        shareText(this, shareBean.title, desc)
    }

    private fun shareMore() {
        if (shareDialog == null) {
            shareDialog = ShareUtils.getBottomDialog(this,false,object :ShareUtils.OnClickListener{
                override fun onClickHelp() {
                    BrowseActivity.startActivity(thisActivity,"https://api.doufu.la/journal/detail?id=745")
                }

                override fun onClickItem(social_type: Int) {
                    val map = HashMap<String, String>()
                    map["type"] = "$social_type"
                    TMAnalysis.event(this@NovelDetailsActivity, UmengEventName.NOVEL_DETAIL_MORE_SHARE_ACTION, map)
                    when (social_type) {
                        ShareType.Poster -> NovelPosterActivity.startActivity(this@NovelDetailsActivity,mPresenter.novelBean)
                        ShareType.CopyLink -> ShareUtils.copyLike(this@NovelDetailsActivity,mPresenter.getShareBean().shareUrl)
                        ShareType.Weibo ->{
                            val shareBean = mPresenter.getShareBean()
                            //我在＃豆花阅读＃ 发现了一本好书《》，作者：豆花昵称，一句话介绍（如果没有就不加）阅读全文>作品链接 #推文# @豆花阅读
                            shareBean.shartText = "我在＃豆花＃ 发现了一本好书《${mPresenter.novelBean.title}》，作者：${mPresenter.novelBean.user.name}，${if (mPresenter.novelBean.recommend_text.isNullOrEmpty()) "" else mPresenter.novelBean.recommend_text}阅读全文>${mPresenter.novelBean.shareUrl} #推文# @豆花阅读"

                            shareBean.social_type = social_type
                            ShareUtils.thirdPartyShare(this@NovelDetailsActivity,shareBean)
                        }
                        else -> {
                            val shareBean = mPresenter.getShareBean()
                            shareBean.social_type = social_type
                            ShareUtils.thirdPartyShare(this@NovelDetailsActivity,shareBean)
                        }
                    }
                }
            })
        }
        shareDialog?.show()
    }

    private fun jumpToComment() {
        val url = "TFComment/TFAllComment.js"
        var map = HashMap<String,Any>()
        map["id"] = mPresenter.novelId
        SimpleWeexActivity.startActivity(this,url,map)
    }


    override fun fillRecommendByAuthor(list: MutableList<NovelRecommendBean>, hasMore: Boolean) {
        if (list != null && list.size > 0) {
            if (hasMore) {
                layRecommendAuthorReplace.visibility = View.VISIBLE
            }else{
                layRecommendAuthorReplace.visibility = View.INVISIBLE
            }
            layRecommendByAuthor.visibility = View.VISIBLE
            val adapter = NovelRecommendGridAdapter(this,4)
            adapter.setData(list)
            val manager = object : GridLayoutManager(this,4){
                override fun canScrollVertically(): Boolean {
                    return false
                }
            }
            rvRecommendByAuthor.layoutManager = manager
            rvRecommendByAuthor.adapter = adapter
        }else{
            layRecommendByAuthor.visibility = View.GONE
        }
        setYouthModel()
    }

    override fun fillRecommendByNovel(list: MutableList<NovelRecommendBean>, hasMore: Boolean) {
        if (list != null && list.size > 0) {
            if (hasMore) {
                layRecommendNovelReplace.visibility = View.VISIBLE
            }else{
                layRecommendNovelReplace.visibility = View.INVISIBLE
            }
            layRecommendByNovel.visibility = View.VISIBLE
            val adapter = NovelRecommendGridAdapter(this,4)
            adapter.setData(list)
            val manager = object :GridLayoutManager(this,4){
                override fun canScrollVertically(): Boolean {
                    return false
                }
            }
            rvRecommendByNovel.layoutManager = manager
            rvRecommendByNovel.adapter = adapter

        }else{
            layRecommendByNovel.visibility = View.GONE
        }
        setYouthModel()
    }

    override fun fillNovelShareRank(bean: NovelShareRankGson) {
        if (bean.list.size > 0) {
            layShareRank.visibility = View.GONE
            ivCrown.visibility = View.VISIBLE
            tvShareRankDesc.text = "已有${bean.count}次分享"
            GlideUtil.displayCircleImageBorder(ivShareUser1,bean.list[0].user.icon,2,Color.parseColor("#ffffff"))
            if (bean.list.size > 1) {
                GlideUtil.displayCircleImageBorder(ivShareUser2,bean.list[1].user.icon,2,Color.parseColor("#ffffff"))
            }
            if (bean.list.size > 2) {
                GlideUtil.displayCircleImageBorder(ivShareUser3,bean.list[2].user.icon,2,Color.parseColor("#ffffff"))
            }
            if (bean.list.size > 3) {
                GlideUtil.displayCircleImageBorder(ivShareUser4,bean.list[3].user.icon,2,Color.parseColor("#ffffff"))
            }
            if (bean.list.size > 4) {
                GlideUtil.displayCircleImageBorder(ivShareUser5,bean.list[4].user.icon,2,Color.parseColor("#ffffff"))
            }
            if (bean.list.size > 5) {
                GlideUtil.displayCircleImageBorder(ivShareUser6,bean.list[5].user.icon,2,Color.parseColor("#ffffff"))
            }
        }else{
            layShareRank.visibility = View.GONE
            ivCrown.visibility = View.GONE
        }
        setYouthModel()
    }

    override fun fillNovelBookList(list: MutableList<NovelBookListBean>) {
        if (list.size > 0) {
            layBookList.visibility = View.GONE
            val adapter = NovelBookListAdapter(this)
            adapter.setData(list)
            val manager = object : LinearLayoutManager(this, VERTICAL,false){
                override fun canScrollVertically(): Boolean {
                    return false
                }
            }
            rvBookList.layoutManager = manager
            rvBookList.adapter = adapter
        }else{
            layBookList.visibility = View.GONE
        }
        setYouthModel()
    }


    private fun setTags(tags:MutableList<TagBean>) {
        layNovelTag.setViewMarginHorizontal(ScreenUtil.dip2px(this, 8f))
        layNovelTag.setViewMarginVertical(ScreenUtil.dip2px(this,9f))
        if (tags != null) {
            layNovelTag.removeAllViews()
            for (i in tags.indices) {
                val text = TextView(this)
                text.isClickable = true
                val params = RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT)
                text.layoutParams = params
                text.textSize = 11f
                text.text = tags[i].name
                text.gravity = Gravity.CENTER
                text.setTextColor(ContextCompat.getColor(this,R.color.text_color_8993A3))
                text.setBackgroundResource(R.drawable.bg_tag_gray)
                text.setPadding(ScreenUtil2.dip2px(7f), ScreenUtil2.dip2px(1f), ScreenUtil2.dip2px(7f), ScreenUtil2.dip2px(1f))
                text.setOnClickListener {
                    TagsUtil.openWeexTagActivity(this@NovelDetailsActivity, tags[i].name, Constant.OBJECT_TYPE_NOVEL, "")
                }
                layNovelTag.addView(text)
            }
        }
    }

    private fun getCatalogDesc(bean: NovelDetailBean):String {
        return if (bean.finished == 1) {
            "完结于${bean.article_num}章"
        }else{
            "连载至${bean.article_num}章 最近更新：${DiaobaoUtil.seconds2TimeString(bean.update_time)}"
        }
    }



    private fun setYouthModel() {
        val pwd = DiaoBaoSharedPreferences.getSharedPreferencesValueToString(SPKey.YOUTH_MODEL_PWD, this, "")
        if (pwd != null && pwd.isNotEmpty()) {
            isYouthModel = true
            layActivityImage.visibility = View.GONE
            layRedEnvelopeMarginTop.visibility = View.GONE
            layRedEnvelope.visibility = View.GONE
            layArticleCommentMarginTop.visibility = View.GONE
            layArticleComment.visibility = View.GONE
            layCommentMarginTop.visibility = View.GONE
            layComment.visibility = View.GONE
            rvHotComment.visibility = View.GONE
            tvToAllComment.visibility = View.GONE
            layAuthorMarginTop.visibility = View.GONE
            tvAuthorTitle.visibility = View.GONE
            layAuthor.visibility = View.GONE
            layShareEnterMarginTop.visibility = View.GONE
            layShareEnter.visibility = View.GONE
            lineShareRank.visibility = View.GONE
            layShareRank.visibility = View.GONE
            layRecommendByAuthor.visibility = View.GONE
            layRecommendByNovel.visibility = View.GONE
            layBookList.visibility = View.GONE
            layTag.visibility = View.GONE
            layShare.visibility = View.GONE
            layShare2.visibility = View.GONE
            layBuyBook.visibility = View.GONE
        }
    }


    override fun fillNovelDetail(bean: NovelDetailBean) {
        var readTime = DiaoBaoSharedPreferences.getSharedPreferencesValueToInt("${SPKey.NOVEL_READ_TIMES}${bean.id}",this,0)
        if (readTime >= 0) {
            DiaoBaoSharedPreferences.setSharedPreferencesValueToInt("${SPKey.NOVEL_READ_TIMES}${bean.id}",readTime+1,this)
        }
        GlideUtil.displayRoundImage(ivNovelCover,bean.thumbnail,3)
        tvNovelTitle.text = bean.title
        tvTopTitle.text = bean.title
        tvAuthorName.text = "${bean.user.name}"
        tvNovelState.text = "${if(bean.pre_collect>0) "预收藏" else if(bean.finished==1) "已完结" else "连载中"} | ${bean.length}字 | ${bean.read_times}次浏览"
        setTags(bean.tags)
        tvDescContent.text = bean.des
        layDesc.setOnClickListener {
            descContentAnimator()
        }
        if (bean.copyright!=null){
            tvCopyright.text = bean.copyright
        }
        if (bean.pre_collect > 0) {
            tvCatalogDesc.text = "作者大大正在存稿中"
            layGift.visibility = View.GONE
        }else{
            tvCatalogDesc.text = getCatalogDesc(bean)
        }
        if (bean.red_envelope_count > 0) {
            tvRedEnvelopeDesc.text = "${bean.red_envelope_count}个"
        }else{
            tvRedEnvelopeDesc.text = ""
        }
//        if (bean.red_envelope_unexpired > 0) {
//            ivRedBag.visibility = View.VISIBLE
//        }else{
//            ivRedBag.visibility = View.GONE
//        }
        tvArticleCommentDesc.text =if (bean.star.isNullOrEmpty()) "" else "${bean.star}分/${bean.star_times}人参与"
        tvCommentDesc.text = if (bean.comment_times!=null) "${bean.comment_times}条" else ""
        tvTicketCount.text = "${bean.month_ticket_sum}"
        tvFlowerCount.text = bean.flowerCount.format()
        tvRewardCount.text = bean.reward_sum.format()
        if (bean.hot_comments != null && bean.hot_comments.size > 0) {
            hotCommentAdapter = NovelHotCommentAdapter(this,bean.user.userId,object :NovelHotCommentAdapter.OnClickPraiseListener{
                override fun onClick(id:Int,position: Int, cancel: Boolean) {
                    if (!AccountService.getInstance().checkAndLogin()) {
                        return
                    }
                    //点赞
                    mPresenter.praiseComment(id,position,cancel)
                }
            })
            hotCommentAdapter!!.setData(bean.hot_comments)
            val manager = object : LinearLayoutManager(this, VERTICAL, false) {
                override fun canScrollVertically(): Boolean {
                    return false
                }
            }
            rvHotComment.layoutManager = manager
            rvHotComment.adapter = hotCommentAdapter
            tvToAllComment.visibility = View.VISIBLE
        }else{
            tvToAllComment.visibility = View.GONE
        }
        GlideUtil.displayCircleImage(ivAuthorHead,bean.user.icon)
        GlideUtil.displayCircleImage(ivAuthorMedal,bean.user.medal)
        layUserGrade.setData(bean.user,false)
        tvAuthorSign.text = bean.user.signature
        setAttention(if (bean.user.following.isNullOrEmpty()) false else bean.user.following.toInt() > 0)
        if (bean.has_fav) {
            ivCollect.setImageResource(R.drawable.icon_collect_novel_st)
        }else{
            ivCollect.setImageResource(R.drawable.icon_collect_novel)
        }
        if (bean.pre_collect > 0) {
            layRead.visibility = View.GONE
            layDownload.visibility = View.GONE
        }
        tvCollectCount.text = bean.collect_times
        tvCollect.text = "${if (bean.pre_collect>0) "预" else ""}收藏"
        tvRead.text = "${if (bean.lastReadPosition>0) "继续阅读" else "免费试读"}"
        setBuyBookActivity(bean)
//        ivVip.visibility = if (bean.is_vip > 0) View.VISIBLE else View.GONE
        ivVipFreeMonth.visibility = if ((bean.vipFree)) View.VISIBLE else View.GONE
        if (AccountService.getInstance().userUid == bean.user.userId) {
            ivEdit.visibility = View.VISIBLE
            ivEdit2.visibility = View.VISIBLE
        }else{
            ivEdit.visibility = View.GONE
            ivEdit2.visibility = View.GONE
        }
        if (bean.activity_link != null && !bean.activity_link.url.isNullOrEmpty()) {
            layActivityEnter.visibility = View.VISIBLE
            tvActivityEnterTitle.text = bean.activity_link.title
            tvActivityEnterDesc.text = bean.activity_link.desc
            layActivityEnter.setOnClickListener {
                BrowseActivity.startActivity(this@NovelDetailsActivity,bean.activity_link.url)
            }
        }else{
            layActivityEnter.visibility = View.GONE
        }

        if (bean.activity_banner.size > 0) {
            layActivityImage.visibility = View.VISIBLE
            GlideUtil.displayImage(ivActivityImage,bean.activity_banner[0].banner_img)
            ivActivityImage.setOnClickListener { ChoiceUtils.clickBanner(this@NovelDetailsActivity,bean.activity_banner[0],"") }
        }else{
            layActivityImage.visibility = View.GONE
        }

        layHead.post {
            val params = RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.MATCH_PARENT, layHead.height)
            ivNovelCoverBg.layoutParams = params
            layNovelCoverBgMask.layoutParams = params
            TFImageViewUtil.showVagueImage(ivNovelCoverBg,bean.thumbnail,160)
        }
        setCopyrightInfo(bean.ip_tags)
        setYouthModel()
    }


    private fun setCopyrightInfo(tags:MutableList<String>){

        if (tags != null && tags.size > 0) {
            layCopyright.visibility = View.VISIBLE
            for (i in tags.indices) {
                val model = tags[i]
                val view = LayoutInflater.from(this).inflate(R.layout.view_ip_tag,null)
                val text = view.findViewById<TextView>(R.id.tvTitle)
                text.text = model
                when {
                    i < 3 -> layIpChild1.addView(view)
                    i < 6 -> layIpChild2.addView(view)
                    i < 9 -> layIpChild3.addView(view)
                    i < 12 -> layIpChild4.addView(view)
                }
            }
        }else{
            layCopyright.visibility = View.GONE
        }
    }


    private fun descContentAnimator() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
            if (tvDescContent.maxLines == 5) {
                tvDescContent.maxLines = 100
                val animation = ObjectAnimator.ofFloat(ivDescArrow,"rotation",0f,180f)
                animation.duration = 500
                animation.start()
            }else{
                tvDescContent.maxLines = 5
                val animation = ObjectAnimator.ofFloat(ivDescArrow,"rotation",180f,0f)
                animation.duration = 500
                animation.start()
            }
        }
    }

    private fun setBuyBookActivity(bean: NovelDetailBean) {
        if (bean.end_price > 0) {
            layBuyBook.visibility = View.VISIBLE
            tvBuyBookTitle.text = bean.fullBuyTxt
            tvBuyBookTotalPrice.paintFlags = Paint.STRIKE_THRU_TEXT_FLAG
            tvBuyBookTotalPrice.text = bean.total_price.toString()

            tvBuyBookActivityPrice.text = bean.end_price.toString()
            if (bean.full_activity.activity_price>0){
                tvBuyBookActivityPrice.text = bean.full_activity.activity_price.toString()
                tvActivityEndTime.text = bean.full_activity.end_time
                layActivityEndTime.visibility = View.VISIBLE

                val time = (TimeDateFunction.getTimeToLong(bean.full_activity.end_time) * 1000 - System.currentTimeMillis())
                timer = object :CustomCountDownTimer(time,1000){
                    override fun onTick(millisUntilFinished: Long) {
                        tvActivityEndTime.text = DateUtils.getDataString(millisUntilFinished)
                    }

                    override fun onFinish() {

                    }

                }
                timer?.start()
            }else{
                layActivityEndTime.visibility = View.GONE
            }
        }else{
            layBuyBook.visibility = View.GONE
        }

    }

    private fun setAttention(isAttention: Boolean) {
        if (isAttention) {
            tvAttention.text = "已关注"
            tvAttention.setTextColor(ContextCompat.getColor(this,R.color.text_color_57))
            tvAttention.setBackgroundResource(R.drawable.cycle_red_light)
        }else{
            tvAttention.text = "+关注"
            tvAttention.setTextColor(ContextCompat.getColor(this,R.color.white))
            tvAttention.setBackgroundResource(R.drawable.cycle_red)
        }
    }

    override fun attentionUser(cancel: Boolean, success: Boolean) {
        if (cancel) {
            //取消关注
            if (success){
                setAttention(false)
            }else{
                setAttention(true)
            }
        }else{
            if (success) {
                setAttention(true)
            }else{
                setAttention(false)
            }
        }
    }

    override fun collectNovel(isCollect: Boolean, collectTimes:Int) {
        if(isCollect){
            ivCollect.setImageResource(R.drawable.icon_collect_novel_st)
        }else{
            ivCollect.setImageResource(R.drawable.icon_collect_novel)
        }
        tvCollect.text = "收藏"
        tvCollectCount.text = collectTimes.toString()
    }

    override fun praiseComment(position: Int, cancel: Boolean, success: Boolean) {
        if (success && hotCommentAdapter != null && hotCommentAdapter?.dataList?.size!! > position) {
            if (cancel) {
                hotCommentAdapter!!.dataList[position].like_times-=1
                hotCommentAdapter!!.dataList[position].has_liked = 0
            }else{
                hotCommentAdapter!!.dataList[position].has_liked = 1
                hotCommentAdapter!!.dataList[position].like_times+=1
            }
            hotCommentAdapter!!.notifyDataSetChanged()
        }
    }

    override fun buyFullBook() {
        layBuyBook.visibility = View.GONE
    }

    override fun showErrorView(error: String) {

    }

    override fun finish() {
        var readTime = DiaoBaoSharedPreferences.getSharedPreferencesValueToInt("${SPKey.NOVEL_READ_TIMES}${mPresenter.novelId}",this,0)
        if (!mPresenter.hasCollect && readTime > 2) {
            //弹出收藏框
            toastCollectDialog()
            //将值设置成-1，不再弹出
            DiaoBaoSharedPreferences.setSharedPreferencesValueToInt("${SPKey.NOVEL_READ_TIMES}${mPresenter.novelId}",-1,this)
        }else{
            super.finish()
        }
    }


    private fun toastCollectDialog() {
        val dialog = DoubleBtnTiptDialog(this,R.style.updateDialog,
                "喜欢就收藏吧","收藏后，作品更新将第一时间收到提醒","以后再说", "收藏作品",
                DoubleBtnTiptDialog.CallBack {
                    //取消
                    finish()
                },DoubleBtnTiptDialog.CallBack {
                    mPresenter.collectNovel()
                    Observable.timer(300, TimeUnit.MILLISECONDS)
                            .compose(RxJavaHelper.observeOnMainThread(thisActivity))
                            .subscribe { finish() }

        })
        dialog.show()
    }


    override fun onDestroy() {
        super.onDestroy()
        timer?.stop()
        EventBus.getDefault().unregister(this)
    }

    companion object{

        fun startActivity(context: Context, novelId: String) {
            if (!novelId.isNullOrEmpty()) {
                startActivity(context,novelId.toInt())
            }
        }

        fun startActivity(context: Context, novelId: String, flag: Int) {
            if (!novelId.isNullOrEmpty()) {
                startActivity(context,novelId.toInt(),flag)
            }
        }

        fun startActivity(context: Context, novelId: Int) {
            val intent = Intent(context, NovelDetailsActivity::class.java)
            intent.putExtra(Constant.ID, novelId)
            context.startActivity(intent)
        }


        fun startActivity(context: Context, novelId: Int,keyword:String, flag: Int) {
            val intent = Intent(context, NovelDetailsActivity::class.java)
            intent.putExtra(Constant.ID, novelId)
            intent.putExtra(Constant.KEYWORD, keyword)
            intent.flags = flag
            context.startActivity(intent)
        }

        fun startActivity(context: Context, novelId: Int, flag: Int) {
            val intent = Intent(context, NovelDetailsActivity::class.java)
            intent.putExtra(Constant.ID, novelId)
            intent.flags = flag
            context.startActivity(intent)
        }
    }

}